<?php
declare(strict_types=1);

namespace app\admin\model;

use app\common\support\Tree;


class AuthRule extends Base
{

    protected $name = 'system_auth_rule';

    public function parents()
    {
        return $this->hasMany(self::class, 'parent_id', 'id');
    }
    /**
     * 创建前
     *
     * @param AuthRule $model
     *
     * @return mixed|void
     */
    public static function onBeforeInsert($model)
    {
        parent::onBeforeInsert($model);
        $model->create_ip = request()->ip();
        $model->create_time = time();
        $model->update_time = time();
        $model->update_ip = request()->ip();
    }

    /**
     * 更新前
     *
     * @param AuthRule $model
     *
     * @return mixed|void
     */
    public static function onBeforeUpdate($model)
    {
        parent::onBeforeUpdate($model);
        $model->update_time = time();
        $model->update_ip = request()->ip();
    }

    public static function buildTreeList()
    {
        $data = self::field('id as value,parent_id,title as label')->select()->toArray();
        $Tree = new Tree();
        $Tree->withConfig('idKey', 'value');
        $TreeData = $Tree->withConfig('buildChildKey', 'children')
            ->withData($data)
            ->build();

        return $TreeData;
    }
    public static function getTreeList()
    {
        $buildTreeList = self::buildTreeList();
        $data = array_merge([['label' => '无', 'parent_id' => 0, 'value' => 0]], $buildTreeList);
        return $data;
    }

    // 递归生成树形结构
    protected static function getTree($parentId = 0)
    {
        $options = [];
        $rules = self::where('parent_id', $parentId)
            ->order('id asc')
            ->select();

        foreach ($rules as $rule) {
            $option = [
                'parent' => self::where('id', $parentId)->value('title'),
                'method' => $rule->method,
                'label' => $rule->title,
                'value' => $rule->id
            ];

            // 递归查找子节点
            $children = self::getTree($rule->id);
            if (!empty($children)) {
                $option['children'] = $children;
            }

            $options[] = $option;
        }

        return $options;
    }

    public static function getTreeOptions()
    {
        return [
            [
                'label' => '所有选项',
                'parent_id' => 0,
                'value' => 0,
                'children' => self::getTree()
            ]
        ];
    }

}
